console.log("JS start");

function PLB() {
    this.initialized = false;

    // display options
    this.settingsHidden = true;
    this.playersShowAll = false;

    // option data
    this.lastRowIndex = -1;
    this.lastRowAction = "";

    // local main data
    this.id = "PLB_local_name"; // this sucks, you have to set it after creating the object    
    this.aD = {};
    this.players = [];
    // don't do anything else here, first initialize() when Wave is connected

    this.initAdNoWave = function() {
        var tmpDate = new Date();
        this.aD.gmt = -(tmpDate.getTimezoneOffset()/60).toFixed(0);
        this.aD.startDay = tmpDate.getDate();
        this.aD.startMonth = tmpDate.getMonth() + 1;
        this.aD.startYear = tmpDate.getYear();
          if(this.aD.startYear<1000) this.aD.startYear+=1900;
        this.aD.startHours = tmpDate.getHours();
        this.aD.turnLength = 48;
        this.aD.aheadTurns = 5;

        this.aD.hostId = wave.getHost().getId();
        console.log("setting host to " + this.aD.hostId)
    }
    this.initPlayersNoWave = function() {
        // do nothing for now
    }
    this.calculateRights = function() {
        this.rights = PLB.rightsUSER; // for every user
        if (this.viewerId == this.aD.hostId) {this.rights = this.rights | PLB.rightsADMIN;}
        console.log("rights " + this.rights + " viewer " + this.viewerId + " host " + this.aD.hostId)
        // check if player
        // check if mod
    }
    this.initViewer = function () {
        // local user data
        this.viewerId = wave.getViewer().getId();
        this.viewerName = wave.getViewer().getDisplayName();
        this.viewerIcon = wave.getViewer().getThumbnailUrl();
        this.viewerEmail = "";
        this.viewerLink = "";
        var tmpDate = new Date();
        this.viewerGmt = -(tmpDate.getTimezoneOffset()/60).toFixed(0);
        this.calculateRights();
        console.log("local data done");
    }
    this.waveGetAll = function() {
        var jsonAD = wave.getState().get('aD', null);
        if (jsonAD == null) {this.initAdNoWave();} else {
            this.aD = JSON.parse(jsonAD);
        }
        var jsonPlayers = wave.getState().get('players', null);
        if (jsonPlayers == null) {this.initPlayersNoWave();} else {
            this.players = JSON.parse(jsonPlayers);
        }
    }
    this.drawInterfaceBase = function() {
        this.PLBh_body = document.getElementById("PLBh_body");
        this.PLBh_body.innerHTML = "";
        this.infoDiv = document.createElement("DIV");
        this.playersDiv = document.createElement("DIV");
        this.adminDiv = document.createElement("DIV");

        this.infoDiv.className = "PLB_div";
        this.playersDiv.className = "PLB_div";
        this.adminDiv.className = "PLB_div";

        this.infoDiv.id = "PLBhd_info";
        this.playersDiv.id = "PLBhd_players";
        this.adminDiv.id = "PLBhd_aD";

        this.PLBh_body.appendChild(this.infoDiv);
        this.PLBh_body.appendChild(this.playersDiv);
        this.PLBh_body.appendChild(this.adminDiv);
    }
    this.initialize = function() {
                console.log("Initializing");
        this.waveGetAll();
        this.initViewer();
        this.drawInterfaceBase();
        this.initialized = true;
                console.log("Initializing END");
    }

    this.waveSetAd = function () {
        var jsonAd = JSON.stringify(this.aD);
        wave.getState().submitDelta({'aD' : jsonAd});
    }
    this.setAheadTurns = function() {
        var last = -1;
        for (var i = 0; i <this.players.length; i++) {
            if (this.players[i].status != "unclaimed") {last = i;}
        }
        if (last >=0) {this.players.splice(last+1);}
        for (var j = 0; j < this.aD.aheadTurns; j++) {
            this.players[this.players.length] = this.makeUnclaimedRow();
        }
    }
    this.btnSaveSettings = function () {
        this.aD.gmt = parseInt(PLB.getOptionSelectedValue(document.getElementById("PLBh_aD_gmt")));
        this.aD.startDay = parseInt(PLB.getOptionSelectedValue(document.getElementById("PLBh_start_day")));
        this.aD.startMonth = parseInt(PLB.getOptionSelectedValue(document.getElementById("PLBh_start_month")));
        this.aD.startYear = parseInt(document.getElementById("PLBh_start_year").value);
        this.aD.startHours = parseInt(PLB.getOptionSelectedValue(document.getElementById("PLBh_start_hours")));
        this.aD.turnLength = parseInt(document.getElementById("PLBh_turnLength").value);
        this.aD.aheadTurns = parseInt(document.getElementById("PLBh_aheadTurns").value);
        this.setAheadTurns();
        this.drawPlayersDiv();
        this.waveSetAd();
    }

    this.ghtmlAdminDivI = function () {
        var r = ""
        r += "GMT:" + PLB.ghtmlIntChoice(-12, 12, this.aD.gmt, "PLBh_aD_gmt") + "<br/>";
        r += "Start Date ";
        r += "D:" + PLB.ghtmlIntChoice(1, 31, this.aD.startDay, "PLBh_start_day") + " ";
        r += "M:" + PLB.ghtmlIntChoice(1, 12, this.aD.startMonth, "PLBh_start_month") + " ";
        r += "Y:<input type='text' size='4' maxlength='4' value='" + this.aD.startYear + "' id='PLBh_start_year'/> ";
        r += "H:" + PLB.ghtmlIntChoice(0, 23, this.aD.startHours, "PLBh_start_hours") + "<br/>";
        r += "Turn length (H):<input type='text' size='4' maxlength='4' value='" + this.aD.turnLength + "' id='PLBh_turnLength'/></br>";
        r += "Ahead Turns:<input type='text' size='4' maxlength='4' value='" + this.aD.aheadTurns + "' id='PLBh_aheadTurns'/></br>";
        r += "Allow multiple (unused): <br/>";
        r += "<input type='button' onclick='" + this.id + ".btnSaveSettings()' value='Save settings' />"
        return r;
    }
    this.btnShowHideSettings = function() {
        var r = "";
        if (this.settingsHidden) {
            r += "<input type='button' onclick='" + this.id + ".btnShowHideSettings()' value='Hide settings' />";
            r += "</br>"+this.ghtmlAdminDivI();
        } else {
            r += "<input type='button' onclick='" + this.id + ".btnShowHideSettings()' value='Show settings' />";
        }
        this.adminDiv.innerHTML = r;
        this.settingsHidden = !this.settingsHidden;
        gadgets.window.adjustHeight();
    }

    this.drawAdminDiv = function() {
        if(this.settingsHidden) {
            // could be better
            this.adminDiv.innerHTML = "<input type='button' onclick='" + this.id + ".btnShowHideSettings()' value='Show settings' />"
        }
        gadgets.window.adjustHeight();
    }

    this.prepareToDraw = function() {
        // recalculate playing times to local times
        // find current player
    }

    this.makeUnclaimedRow = function() {
        var r = {};
            r.id = null;
            r.icon = "http://km-gadgets.googlecode.com/files/empty.png";
            r.status = "unclaimed";
            r.start = "unused"; //calculate this
            r.name = ""
            r.gmt = 0;
            r.email = ""
            r.link = ""
        return r;
    }
    this.waveSetPlayers = function(){
        var jsonPlayers = JSON.stringify(this.players);
        wave.getState().submitDelta({'players' : jsonPlayers});
    }

    this.btnDoPlayerAction = function(action) {
        switch (action)
        {
            case "": break;
            case null: break;
            case "cancel":
            break;

            case "unclaim":
            this.players[this.lastRowIndex] = this.makeUnclaimedRow();
            this.players[this.lastRowIndex].status = "unclaimed";
            break;

            case "insert":
            this.players.splice(this.lastRowIndex,0, {});
            // no break!
            case "claimModify":
            var r = this.makeUnclaimedRow();
            r.id = this.viewerId;
            r.icon = this.viewerIcon;
            r.status = "ready";
            r.start = "unused"; //calculate this
            r.name = document.getElementById("PLBh_viewerName").value.substr(0, 15);
            r.gmt = parseInt(PLB.getOptionSelectedValue(document.getElementById("PLBh_viewerGmt")));
            r.email = document.getElementById("PLBh_viewerEmail").value;
            r.link = document.getElementById("PLBh_viewerLink").value;
            this.players[this.lastRowIndex] = r;
            break;
        }
        this.setAheadTurns();
        this.waveSetPlayers();
        this.drawPlayersDiv();
    }

    this.ghtmlPlayersOptions = function(name, gmt, email, link) {
        var r = "Player options</br>";
        r += "Name:<input type=text id='PLBh_viewerName' value='"+ name +"' /><br/>"
        r += "GMT:" + PLB.ghtmlIntChoice(-12, 12, gmt, "PLBh_viewerGmt") + "<br/>";
        r += "Email <input type=text id='PLBh_viewerEmail' value='"+ email +"' /><br/>"
        r += "Link <input type=text id='PLBh_viewerLink' value='"+ link +"' /><br/>"
        if(this.lastRowAction == "modify") {
            r += "<input type='button' onclick='" + this.id + ".btnDoPlayerAction(\"unclaim\")' value='unclaim ("+ (this.lastRowIndex+1) +")' />";
            r += "<input type='button' onclick='" + this.id + ".btnDoPlayerAction(\"claimModify\")' value='"+ this.lastRowAction +" ("+ (this.lastRowIndex+1) +")' />";
        } else if (this.lastRowAction == "claim") {
            r += "<input type='button' onclick='" + this.id + ".btnDoPlayerAction(\"claimModify\")' value='"+ this.lastRowAction +" ("+ (this.lastRowIndex+1) +")' />";
        } else if (this.lastRowAction == "insert") {
            r += "<input type='button' onclick='" + this.id + ".btnDoPlayerAction(\"insert\")' value='"+ this.lastRowAction +" ("+ (this.lastRowIndex+1) +")' />";
        }
        r += "<input type='button' onclick='" + this.id + ".btnDoPlayerAction(\"cancel\")' value='cancel' />";
        return r;
    }

    this.btnClaim = function(rowIndex) {
        this.lastRowIndex = rowIndex;
        this.lastRowAction = "claim";
        this.drawPlayersDiv();
        this.playersDiv.innerHTML += this.ghtmlPlayersOptions(this.viewerName, this.viewerGmt, this.viewerEmail, this.viewerLink);
        gadgets.window.adjustHeight();
    }
    this.btnModify = function(rowIndex) {
        this.lastRowIndex = rowIndex;
        this.lastRowAction = "modify";
        this.drawPlayersDiv();
        this.playersDiv.innerHTML += this.ghtmlPlayersOptions(this.players[rowIndex].name, this.players[rowIndex].gmt, this.players[rowIndex].email, this.players[rowIndex].link);
        gadgets.window.adjustHeight();
    }
    this.btnInsert = function(rowIndex) {
        this.lastRowIndex = rowIndex;
        this.lastRowAction = "insert";
        this.drawPlayersDiv();
        this.playersDiv.innerHTML += this.ghtmlPlayersOptions(this.viewerName, this.viewerGmt, this.viewerEmail, this.viewerLink);
        gadgets.window.adjustHeight();
    }
    this.btnKick = function(rowIndex) {
        this.lastRowIndex = rowIndex;
        this.lastRowAction = "kick";
        this.players[this.lastRowIndex] = this.makeUnclaimedRow();
        this.players[this.lastRowIndex].status = "unclaimed";
        this.btnDoPlayerAction();
    }
    this.btnForbid = function(rowIndex) {
        this.lastRowIndex = rowIndex;
        this.lastRowAction = "forbid";
        this.players[this.lastRowIndex] = this.makeUnclaimedRow();
        this.players[this.lastRowIndex].status = "forbidden";
        this.btnDoPlayerAction();
    }
    this.btnDelete = function(rowIndex) {
        this.lastRowIndex = rowIndex;
        this.lastRowAction = "delete";
        this.players.splice(rowIndex, 1);
        this.btnDoPlayerAction();
    }
    this.btnMoveUp = function(rowIndex) {
        if (rowIndex > 0) {
            this.lastRowIndex = rowIndex;
            this.lastRowAction = "moveUp";
            var tmp = this.players[this.lastRowIndex-1];
            this.players[this.lastRowIndex-1] = this.players[this.lastRowIndex];
            this.players[this.lastRowIndex] = tmp;
            this.btnDoPlayerAction();
        }
    }
    this.btnMoveDown = function(rowIndex) {
        this.lastRowIndex = rowIndex;
        this.lastRowAction = "moveDown";
        var tmp = {};
        if (rowIndex < this.players.length-1) {
            tmp = this.players[this.lastRowIndex+1];
        } else {
            tmp = this.makeUnclaimedRow();
        }
        this.players[this.lastRowIndex+1] = this.players[this.lastRowIndex];
        this.players[this.lastRowIndex] = tmp;
        this.btnDoPlayerAction();
    }

    this.ghtmlPlayersLineI = function (row) {
        var r = "<tr>";
        r += "<td>" + (row+1) + "</td>";
        r += "<td><img src='" + this.players[row].icon + "'  width='22' height='22'></td>";
        r += "<td>" + this.players[row].name + "</td>";
        r += "<td>" + this.players[row].status + "</td>";
        r += "<td>" + this.players[row].start + "</td>";
        r += "<td><a href='" + this.players[row].link + "'>link</a></td>";
        r += "<td>"
        if (this.players[row].status == "unclaimed") {r += "<a href='javascript:" + this.id + ".btnClaim(" + row +")' title='Claim'>Claim </a>";}
        if (this.viewerId == this.players[row].id) {r += "<a href='javascript:"+ this.id + ".btnModify(" + row +")' title='Modify'>Modify </a>";}
        if (this.rights >= PLB.rightsMOD) {r+= "<a href='javascript:" + this.id + ".btnKick(" + row +")' title='Kick'>K </a>";}
        if (this.rights >= PLB.rightsMOD) {r += "<a href='javascript:" + this.id + ".btnInsert(" + row +")' title='Insert'>I </a>";}
        if (this.rights >= PLB.rightsMOD) {r += "<a href='javascript:" + this.id + ".btnMoveUp(" + row +")' title='Move Up'>U </a>";}
        if (this.rights >= PLB.rightsMOD) {r += "<a href='javascript:" + this.id + ".btnMoveDown(" + row +")' title='MoveDown>D </a>";}
        if (this.rights >= PLB.rightsMOD) {r += "<a href='javascript:" + this.id + ".btnForbid(" + row +")' title='Forbid'>F </a>";}
        if (this.rights >= PLB.rightsMOD) {r += "<a href='javascript:" + this.id + ".btnDelete(" + row +")' title='Delete'>X </a>";}
        r += "</td>";
        r += "</tr>";
        return r;
    }

    this.ghtmlPlayersDivI = function(from, to) {
        var r = "<table class='PLB_table' />";
        r += "<tr><th>No</th><th>Icon</th><th>Name</th><th>Status</th><th>Start</th><th>Info</th><th>EDIT</th></tr>";
        for(var i = from; i< to; i++) {
            r += this.ghtmlPlayersLineI(i);
        }
        r += "</table>";
        return r;
    }

    this.drawPlayersDiv = function() {
        // enumerate players from playersDrawStart to playersDrawEnd, draw every line
        var from = 0;
        var to = this.players.length;
        var r = this.ghtmlPlayersDivI(from, to);
        // here add show all button and buttons for scrolling r+=
        this.playersDiv.innerHTML = r;
        gadgets.window.adjustHeight();
    }
    
    this.stateUpdated = function() {
        if (!this.initialized) {this.initialize();} else {
            this.waveGetAll();
            this.calculateRights();}
            console.log("drawing players ")
            this.prepareToDraw();
            this.drawPlayersDiv();

        if (this.rights & PLB.rightsADMIN) {this.drawAdminDiv();} else {
                this.adminDiv.innerHTML = "No admin rights, ignore this.";}
        // prepare for drawing
        // draw info
    }

}

PLB.rightsUSER = 1;
PLB.rightsPLAYER = 2
PLB.rightsMOD = 4;
PLB.rightsADMIN = 8;

PLB.ghtmlIntChoice = function(from, to, sel, id, cls) {
    var r = "<select " + (cls ? "class='" + cls + "' " : "") + (id ? "id='" + id + "'" : "") + ">";
    for (i=from;i<=to;i++) {
        r += "<option value='" + i + "'" + (sel == i ? " selected" : "") + ">" + i + "</option>"
    }
    return r + "</select>";
}
PLB.selectOptionByValue = function(selObj, val){
    var A= selObj.options, L= A.length;
    while(L){
        if (A[--L].value== val){
            selObj.selectedIndex= L;
            L= 0;
        }
    }
}
PLB.getOptionSelectedValue = function(selObj){
    var a = selObj.selectedIndex;
    var b = selObj.options;
    var c = b[a].value;
    return c;
}

var PLB_local_name = new PLB();

function stateUpdated() {
    PLB_local_name.stateUpdated();
}

function init() {if (wave && wave.isInWaveContainer()) {wave.setStateCallback(stateUpdated);}}
gadgets.util.registerOnLoadHandler(init);


console.log("Script log: END: All loaded.")